package com.spice.service.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spice.common.constant.PermissionConstant;
import com.spice.common.exception.SpiceException;
import com.spice.common.model.BaseEntity;
import com.spice.common.result.Response;
import com.spice.common.result.ResultCodeEnum;
import com.spice.common.util.CheckUtil;
import com.spice.service.entity.enums.TableEnum;
import com.spice.service.entity.form.SaveBatchForm;
import com.spice.service.entity.pojo.*;
import com.spice.service.util.ExcelUtil;
import com.spice.service.util.MultipartFileUtil;
import com.spice.service.util.ServiceUtil;
import com.spice.service.util.ShiroUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/port")
public class PortController {

    @Autowired
    ServiceUtil serviceUtil;

    @ApiOperation(value = "预览导入数据",
            notes = "预览完数据后，若要导入数据。" +
                    "请调用tableName对应的Controller中的saveBatch接口")
    @PostMapping(value = "/previewImport/{tableName}", produces = "application/json;charset=UTF-8")
    public Response previewImport(@PathVariable("tableName") String tableName,
                                  MultipartFile multipartFile) {
        if (!ShiroUtil.isAuthenticated()) {
            return Response.setResult(ResultCodeEnum.NO_AUTHENTICATION);
        }
        if (CheckUtil.objectsHasNull(tableName,
                multipartFile)) {
            return Response.setResult(ResultCodeEnum.PARAM_LACK);
        }
        // 根据输入的tableName寻找相应对象
        TableEnum table = null;
        for (TableEnum value : TableEnum.values()) {
            if (value.getTableName().equals(tableName)) {
                table = value;
            }
        }
        if (table == null) {
            throw new SpiceException().message("表名输入错误");
        }
        // 上传文件
        FileInfo fileInfo = MultipartFileUtil.saveFile(multipartFile);
        String absolutePath = new File(MultipartFileUtil.saveFileFolder,
                fileInfo.getLocalFileName())
                .getAbsolutePath();
        // 读取所上传的文件，并以相应的对象进行解析
        List<BaseEntity> read = ExcelUtil.read(absolutePath, table.getTableClass());
        return Response.ok().data("objectList", read);
    }

    @ApiOperation("导出数据")
    @GetMapping(value = "/exportData/{tableName}", produces = "application/json;charset=UTF-8")
    public Response exportData(@PathVariable("tableName") String tableName,
                               HttpServletRequest request) {
        if (!ShiroUtil.isAuthenticated()) {
            return Response.setResult(ResultCodeEnum.NO_AUTHENTICATION);
        }
        TableEnum table = null;
        for (TableEnum value : TableEnum.values()) {
            if (value.getTableName().equals(tableName)) {
                table = value;
            }
        }
        if (table == null) {
            throw new SpiceException().message("表名输入错误");
        }

        String newName = "export"
                + "_"
                + new Date().getTime()
                + ".xlsx";

        String absolutePath = new File(MultipartFileUtil.saveFileFolder, newName)
                .getAbsolutePath();
        // 从数据库获取所有对象
        List<?> list = serviceUtil.getServiceMap().get(tableName).list();

        ExcelUtil.write(absolutePath, table.getTableClass(), list);

        return Response.ok()
                .data("downloadUrl",
                        new FileInfo("", newName)
                                .loadUrl(request).getDownloadUrl());
    }

    @ApiOperation("导出数据模板")
    @GetMapping(value = "/exportDataTemplate/{tableName}", produces = "application/json;charset=UTF-8")
    public Response exportDataTemplate(@PathVariable("tableName") String tableName,
                               HttpServletRequest request) {
        if (!ShiroUtil.isAuthenticated()) {
            return Response.setResult(ResultCodeEnum.NO_AUTHENTICATION);
        }
        TableEnum table = null;
        for (TableEnum value : TableEnum.values()) {
            if (value.getTableName().equals(tableName)) {
                table = value;
            }
        }
        if (table == null) {
            throw new SpiceException().message("表名输入错误");
        }

        String newName = "export"
                + "_"
                + new Date().getTime()
                + ".xlsx";

        String absolutePath = new File(MultipartFileUtil.saveFileFolder, newName)
                .getAbsolutePath();

        ExcelUtil.write(absolutePath, table.getTableClass(), null);

        return Response.ok()
                .data("downloadUrl",
                        new FileInfo("", newName)
                                .loadUrl(request).getDownloadUrl());
    }
}
